#region Using Directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Secure.Common;

#endregion

namespace Secure.Client
{
    public class SecureClient : ISecureClient
    {
        private readonly string _applicationId;
        private readonly string _applicationKey;
        private readonly IIdentityProvider _identityProvider;
        private readonly IGatewayService _gatewayService;

        private string _currentServiceToken = "";

        public SecureClient(string applicationId, string applicationKey)
            : this(applicationId, applicationKey, new HybridIdentityProvider(), new GatewayServiceClient())
        {
            _applicationId = applicationId;
            _applicationKey = applicationKey;
        }

        public SecureClient(string applicationId, string applicationKey, IIdentityProvider identityProvider, IGatewayService gatewayService)
        {
            _applicationId = applicationId;
            _applicationKey = applicationKey;
            _identityProvider = identityProvider;
            _gatewayService = gatewayService;
        }

        private string GetServiceToken()
        {
            if (string.IsNullOrEmpty(_currentServiceToken))
            {
                _currentServiceToken = _gatewayService.GetSecurityToken(_applicationId, _applicationKey);
            }

            return _currentServiceToken;
        }

        public bool IsUserInRole(string username, string roleName, out string[] additionalParams)
        {
            if (string.IsNullOrEmpty(username))
            {
                if (!_identityProvider.CurrentUserIsIdentified)
                {
                    throw new ArgumentException("Unable to determine the current user.", "username");
                }

                username = _identityProvider.CurrentUserId;
            }

            if (string.IsNullOrEmpty(roleName))
            {
                throw new ArgumentException("roleName");
            }

            SecuredResource appResource = new ApplicationResource(_applicationId, roleName);
            string token = GetServiceToken();
            bool isAuthorised = _gatewayService.IsAllowedAccess(out additionalParams, token, username, appResource.GetResourcePath());

            return isAuthorised;
        }

        public void AddUserToRole(string username, string roleName, params string[] additionalParams)
        {
            throw new System.NotImplementedException();
        }

        public void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new System.NotImplementedException();
        }

        public void CreateRole(string roleName)
        {
            throw new System.NotImplementedException();
        }
    }
}